// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import ComponentBase from "../../../general/Script/component/ComponentBase";
import DataMgr from "../../../general/Script/mgr/dataManager";
import GameMgr from "../../../general/Script/mgr/gameManager";
import NativeMgr from "../../../general/Script/mgr/nativeManager";
import NetMgr from "../../../general/Script/mgr/netManager";




const { ccclass, property } = cc._decorator;

@ccclass
export default class UserInfo extends ComponentBase {


    coinLeft: cc.Node = null;
    serverGet: cc.Node = null;

    listItem: cc.Node = null;
    adInfo: cc.Node = null;
    phoneInfo: cc.Node = null;
    list: cc.Node = null;

    uid: cc.Node = null;
    moreCoin: cc.Node = null;
    sendUid: cc.Node = null;
    sendCoin: cc.Node = null;

    coinInfo: cc.Node = null;
    coinList: cc.Node = null;
    coinItem: cc.Node = null;

    userInfo: cc.Node = null;
    listInfo: cc.Node = null;

    onLoad(): void {
        super.onLoad()

        cc.systemEvent.on('toggleButtonCallBack', this.moduleChange.bind(this), this);
    }
    start() {
        this.coinLeft.getComponent(cc.Label).string = DataMgr.Ins().userInfo.coin;
        this.serverGet.getComponent(cc.Label).string = Math.floor(DataMgr.Ins().userInfo.redPack / 10);
        this.uid.getComponent(cc.Label).string = DataMgr.Ins().uid;



        this.initList();
        this.refreshAdInfo()
        this.moduleChange('userInfo');

    }


    initList() {
        this.list.removeAllChildren();
        const listInfo = DataMgr.Ins().userInfo.list;


        for (let i = 0; i < listInfo.length; i++) {
            const info: any = listInfo[i];
            const node = cc.instantiate(this.listItem);
            // const info = {
            //     RitType: infoStr[8],
            //     SdkName: infoStr[2],
            //     Ecpm: infoStr[1],
            //     SlotId: infoStr[4],
            //     RequestId: infoStr[7],
            //     time: Date.now(),
            //     userGet: userGet,
            //     serverGet: ecpm - userGet
            // }
            node.getChildByName('RitType').getComponent(cc.Label).string = this.getRitType(info.RitType);
            node.getChildByName('SdkName').getComponent(cc.Label).string = this.getSdkName(info.SdkName);

            // node.getChildByName('serverGet').getComponent(cc.Label).string = (info.serverGet / 100000).toFixed(3);
            node.getChildByName('Ecpm').getComponent(cc.Label).string = Math.floor(info.Ecpm / 10);
            node.getChildByName('time').getComponent(cc.Label).string = DataMgr.Ins().formateDataByTime(info.time, true);

            node.active = true;
            node.parent = this.list;
        }
    }

    getRitType(ritType) {
        const sdkNameMap = {
            'splash': '开屏',
            'banner': '底部广告',
            'interstitialFull': '插屏广告',
            'rewardVideo': '激励广告',
            'feed': '占屏广告',
        }

        return sdkNameMap[ritType] || ritType;
    }
    getSdkName(sdkName) {
        const sdkNameMap = {
            'pangle': '抖音穿山甲',
            'gdt': '腾讯优量汇',
            'ks': '快手',
            'baidu': '百度',
        }

        return sdkNameMap[sdkName] || sdkName;
    }
    moduleChange(type) {
        console.log('moduleChange', type);
        const names = ['userInfo', 'listInfo', 'coinInfo'];
        if (names.indexOf(type) < 0) {
            return;
        }
        this.userInfo.active = type == 'userInfo';
        this.listInfo.active = type == 'listInfo';
        this.coinInfo.active = type == 'coinInfo';
        if (this.coinInfo.active) {
            this.refreshCoinList()
        }
    }


    closeBtnCallBack() {
        this.node.removeFromParent(true);
        this.node.destroy()
    }

    onDestroy(): void {
        super.onDestroy();

        cc.systemEvent.targetOff(this);
    }


    async refreshAdInfo() {
        const begin = DataMgr.Ins().formatData();
        const end = DataMgr.Ins().formatData(1);

        const deviceId = NativeMgr.Ins().deviceId();
        const appId = NativeMgr.Ins().appId();

        const adInfoJson: any = {
            totalfinish: 0,
            totalMoney: 0,
            totalClick: 0,

            finish: 0,
            money: 0,
            click: 0,
            reward: 0
        }

        const infoTotal = await NetMgr.Ins().servo.get(`/payment/advertising/aggs?appid=${appId}&begin=${begin}&end=${end}`);
        console.log('infoTotal = ', infoTotal);
        if (infoTotal.status === 200) {
            const arr = infoTotal.body;
            for (let i in arr) {
                const item = arr[i];
                if (item.event === 'finish') {
                    adInfoJson.totalfinish = item.count || 0;
                    adInfoJson.totalMoney = (item.total || 0) / 100000;
                } else if (item.event === 'click') {
                    adInfoJson.totalClick = item.count || 0;
                }
            }
        }

        const info = await NetMgr.Ins().servo.get(`/payment/advertising/aggs?appid=${appId}&unionid=${deviceId}&begin=${begin}&end=${end}`);
        console.log('info = ', info);
        if (info.status === 200) {
            const arr = info.body;
            for (let i in arr) {
                const item = arr[i];
                if (item.event === 'finish') {
                    adInfoJson.finish = item.count || 0;
                    adInfoJson.money = (item.total || 0) / 100000;
                } else if (item.event === 'click') {
                    adInfoJson.click = item.count || 0;
                } else if (item.event === 'reward') {
                    adInfoJson.reward = item.count || 0;
                }
            }
        }


        console.log('info = ', adInfoJson);

        this.adInfo.getComponent(cc.Label).string = `总完:${adInfoJson.totalfinish}，总点击:${adInfoJson.totalClick}，总点率:${(adInfoJson.totalClick / adInfoJson.totalfinish).toFixed(2)}，今日得:${adInfoJson.totalMoney.toFixed(2)}元\n单完:${adInfoJson.finish}次，激励:${adInfoJson.reward}次，点击:${adInfoJson.click}次，点击率:${(adInfoJson.click / adInfoJson.finish).toFixed(2)}，得:${adInfoJson.money.toFixed(2)}元`

        this.phoneInfo.getComponent(cc.Label).string = `deviceId:${deviceId}\nappId:${appId}`;
        console.log('deviceId = ', deviceId);
    }


    changeCoin() {
        const coin = this.sendCoin.getComponent(cc.EditBox).string;
        if (Number(coin) < 100) {
            this.moreCoin.getComponent(cc.Label).string = "最少赠送100金币";
            return;
        }

        this.moreCoin.getComponent(cc.Label).string = Math.floor(Number(coin) * 0.05);
    }

    async sendBtnCallBack() {
        const uid = this.sendUid.getComponent(cc.EditBox).string;
        const coin = this.sendCoin.getComponent(cc.EditBox).string;
        const coinMore = this.moreCoin.getComponent(cc.Label).string;

        const needCoin = Number(coin) + Number(coinMore);

        if (DataMgr.Ins().userInfo.coin < needCoin) {
            GameMgr.Ins().showMsg('金币不足');
            return;
        }

        if (Number(coin) < 100) {
            GameMgr.Ins().showMsg('最少赠送100金币');
            return;
        }

        if (uid == '' || uid == DataMgr.Ins().uid) {
            GameMgr.Ins().showMsg('请输入对方uid');
            return;
        }


        const infoTotal = await NetMgr.Ins().servo.post(`/profile/transfer/${DataMgr.Ins().token}`, { uid: uid, coin: Number(coin) }, true);
        console.log('infoTotal = ', infoTotal);
        if (infoTotal.status === 200) {
            const info = infoTotal.body;
            // {status:'ok', user:{ coin:xxxx} }
            if (info.status === 'ok') {
                DataMgr.Ins().userInfo.coin = info.user.coin;
                this.coinLeft.getComponent(cc.Label).string = DataMgr.Ins().userInfo.coin;
                GameMgr.Ins().showMsg('赠送成功');
            }
        }



    }


    async refreshCoinList() {
        this.coinList.destroyAllChildren();

        // /profile/coinlogs?begin="YYYY-MM-DD"&end="YYYY-MM-DD"&page=1&length=20
        // { rows: {_message: string; _timestamp: string; uid: string; content: Object}[], total }
        // _message: string; _timestamp: string; event: string; uid: string; content: Object

        const begin = DataMgr.Ins().formatData();
        const end = DataMgr.Ins().formatData(1);


        const page = 1;
        const length = 20;
        GameMgr.Ins().block()
        const list = await NetMgr.Ins().servo.get(`/profile/coinlogs?begin=${begin}&end=${end}&page=${page}&length=${length}`);
        GameMgr.Ins().unblock();
        console.log('list = ', list);
        if (list.status === 200) {
            const arr = list.body.rows;
            const total = list.body.total;
            for (let i in arr) {
                const item = arr[i];
                const node = cc.instantiate(this.coinItem);
                node.active = true;
                this.coinList.addChild(node);
                node.getChildByName('event').getComponent(cc.Label).string = item._message;
                node.getChildByName('coin').getComponent(cc.Label).string = item['content.coin'];
                node.getChildByName('uid').getComponent(cc.Label).string = item.uid;
                node.getChildByName('time').getComponent(cc.Label).string = DataMgr.Ins().formateDataByTime(item.__time___0 * 1000, true);
            }
        }
    }

}
